package nio.timeServerTest;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Date;
import java.util.Iterator;
import java.util.Set;

/**
 * Created by Administrator on 2017/3/14 0014.
 */
public class TimeServer implements Runnable{

    private Integer port = 8110;

    private Selector selector;

    private ServerSocketChannel serverSocketChannel;

    private Boolean isRunning = Boolean.TRUE;

    public static void main(String[] args) {
        TimeServer timeServer = new TimeServer();
        new Thread(timeServer).start();
    }

    public  TimeServer(){
        try {
            selector = Selector.open();
            serverSocketChannel = ServerSocketChannel.open();
            serverSocketChannel.configureBlocking(false);
            serverSocketChannel.bind(new InetSocketAddress(port));
            serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
            System.out.println("server started");
        } catch (IOException e) {
            e.printStackTrace();
            System.exit(1);
        }
    }

    public void stop(){
        this.isRunning = Boolean.FALSE;

    }

    private void handle(SelectionKey selectionKey){
        try {
            if(selectionKey.isValid()){
                if(selectionKey.isAcceptable()){
                    ServerSocketChannel ssc = (ServerSocketChannel)selectionKey.channel();
                    SocketChannel channel =  ssc.accept();
                    channel.configureBlocking(false);
                    channel.register(selector,SelectionKey.OP_READ);
                }else if(selectionKey.isReadable()){
                    SocketChannel socketChannel = (SocketChannel)selectionKey.channel();
                    ByteBuffer buffer = ByteBuffer.allocate(1024);
                    int readByte = socketChannel.read(buffer);
                    if(readByte > 0){
                        buffer.flip();
                        byte[] bytes = new byte[buffer.remaining()];
                        buffer.get(bytes);
                        String content = new String(bytes);
                        System.out.println("recv :" + content);

                        String result = new Date().toString();
                        ByteBuffer writeBuf = ByteBuffer.allocate(result.getBytes().length);
                        writeBuf.put(result.getBytes());

                        writeBuf.flip();
                        socketChannel.write(writeBuf);
                    }
                }
            }
        } catch (IOException io){
            try {
                if(selectionKey.channel() != null){
                    selectionKey.channel().close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        while (isRunning){
            try {
                selector.select();
                Set<SelectionKey> selectionKeys = selector.selectedKeys();
                Iterator<SelectionKey> iterator = selectionKeys.iterator();
                while (iterator.hasNext()){
                    SelectionKey key = iterator.next();
                    iterator.remove();
                    this.handle(key);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
